package com.fenxiao.mytask.action;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.fenxiao.common.Pager;
import com.fenxiao.mytask.entity.UserTask;
import com.fenxiao.mytask.service.UserTaskService;
import com.fenxiao.record.entity.Commissionrecord;
import com.fenxiao.record.entity.FreeAmount;
import com.fenxiao.record.entity.IncomeRecode;
import com.fenxiao.record.service.CommissionrecordService;
import com.fenxiao.record.service.FreeAmountService;
import com.fenxiao.record.service.IncomeRecodeService;
import com.fenxiao.task.entity.Task;
import com.fenxiao.task.entity.TaskScreenshot;
import com.fenxiao.task.service.TaskService;
import com.fenxiao.user.entity.User;
import com.fenxiao.user.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class UserTaskAction extends ActionSupport {
	private HttpServletRequest request;
	private HttpServletResponse response;
	private UserTaskService userTaskService;
	private HttpSession session;

	private UserService userService;
	private Map<String, Object> dataMap;

	private List<UserTask> usertaskList;

	private int page=1;
	private List<TaskScreenshot> shotList;
	private Pager pageBean;
	private String search;

	private UserTask usertask;
	private User user;
	private Task task;
	private Commissionrecord commissionrecord;
	private IncomeRecode incomeRecode;
	private FreeAmount freeAmount;
	private File fileTest; // 接收这个上传的文件
	private String fileTestFileName;
	private File fileTest1; // 接收这个上传的文件
	private String fileTest1FileName;

	private String msg;
	private String content;
	private String number;

	private TaskService taskService;
	private CommissionrecordService commissionrecordService;
	private IncomeRecodeService incomeRecodeService;
	private FreeAmountService freeAmountService;
	//任务佣金
	public String queryThoseTaskCompleted() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		int userId = Integer.parseInt(request.getParameter("userId"));
		  User user1 = userService.queryuserById(userId);
		//分页查询任务奖金
		Pager pagelist = userTaskService.queryTaskMyyj(10, page, userId);
		    List pagetask = pagelist.getList();
		int Total = pagelist.getTotalPage();
//		List<UserTask> list = userTaskService.queryThoseTaskCompleted(Long
//				.parseLong(request.getParameter("userId")));
//		request.setAttribute("list", list);
		request.setAttribute("pagetask", pagetask);
		request.setAttribute("Total", Total);
		request.setAttribute("page", page);
		request.setAttribute("openId", user1.getWeChatId());

		return "queryThoseTaskCompleted";
	}
	//团队奖金
	public String queryTeamTaskForTheMan() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		User user = userService.queryuserById(Long.parseLong(userId));
		//分页查询团队佣金
		Pager pagelist = userTaskService.queryTaskPagetuangdui(10, page, user);
		List pagetuandui = pagelist.getList();
		//页数
		 int Total = pagelist.getTotalPage();
		  
//		List list = userTaskService.queryTeamTaskForTheMan(user);
//		request.setAttribute("list", list);
		 request.setAttribute("Total", Total);
		 request.setAttribute("pagetuandui", pagetuandui);
		 request.setAttribute("page", page);
		request.setAttribute("openId", user.getWeChatId());
		return "queryTeamTaskForTheMan";
	}
	//通过状态分页查询查询
	 public String uploadTimeuploadTime() throws Exception{
		 request = ServletActionContext.getRequest();
		 response = ServletActionContext.getResponse();
//		 openId="+openId+"&taskStatus="+value+"&taskType=
//			"+taskType+"&taskPrice="+taskPrice
		 String openId = request.getParameter("openId");
		 String taskType = request.getParameter("taskType");
		 String taskPrice = request.getParameter("taskPrice");
		 String taskStatus = request.getParameter("taskStatus");
		 User user1 = userService.queryMoneyOfUser(openId);
		     long userid = user1.getId();
		 Integer taskType1=null;
		 Integer taskPrice1=null;
		 Integer taskStatus1 = null;
		 if(taskType!=null&&!"".equals(taskType)){
			 taskType1= Integer.parseInt(taskType);
			request.setAttribute("taskType", taskType1); 
		 }
		 if(taskPrice!=null&&!"".equals(taskPrice)){
			  taskPrice1 = Integer.parseInt(taskPrice);
			 request.setAttribute("taskPrice", taskPrice1);
		 }
		 if(taskStatus!=null&&!"".equals(taskStatus)){
			taskStatus1 = Integer.parseInt(taskStatus);
			 request.setAttribute("taskStatus", taskStatus1);
		 }
		     //分页
		      Pager pagelist = userTaskService.queryMyTaskZt(10, page, userid, taskStatus1, taskType1, taskPrice1);
		      List pagetask = pagelist.getList();
		      int Total = pagelist.getTotalPage();
//		    List<UserTask> list = userTaskService.shaixuan(user1.getId(), taskStatus1, taskType1,taskPrice1);
//		    	request.setAttribute("list", list);
		    	request.setAttribute("openId", openId);
		    	request.setAttribute("Total", Total);
		    	request.setAttribute("page", page);
		    	request.setAttribute("pagetask", pagetask);
				return "index";
		 
	 }
	
	
	//推广佣金
	public String queryTeamTaskForTheMan2() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		User user = userService.queryuserById(Long.parseLong(userId));
		//分页查询数据
		Pager pagetuiguang = userTaskService.queryTaskPagetuiguan(10, page, user);
		List tuiguanglist = pagetuiguang.getList();
//		List list = userTaskService.queryTeamTaskForTheMan(user);
//		System.err.println("list+----------"+list);
		//总页数
		int Total = pagetuiguang.getTotalPage();
//		request.setAttribute("list", list);
		request.setAttribute("Total", Total);
		request.setAttribute("page", page);
		request.setAttribute("tuiguanglist", tuiguanglist);
		request.setAttribute("openId", user.getWeChatId());
		return "queryTeamTaskForTheMan2";
	}

	public String queryTaskForTheMan() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String openId = request.getParameter("openId");
		User user = userService.queryMoneyOfUser(openId);
		List<UserTask> list = userTaskService.queryPeopleTask(user.getId());
		request.setAttribute("list", list);
		request.setAttribute("openId", openId);
		return "index";
	}

	public String shaixuan() throws ParseException {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();

		String openId = request.getParameter("openId");
		String status = request.getParameter("taskStatus");
		String type = request.getParameter("taskType");
		String price = request.getParameter("taskPrice");
		User user = userService.queryMoneyOfUser(openId);
		Integer taskStatus = null;
		Integer taskType = null;
		Integer taskPrice = null;
		if (status != null && !status.equals("")) {
			taskStatus = Integer.parseInt(status);
			request.setAttribute("taskStatus", taskStatus);
		}
		if (type != null && !type.equals("")) {
			taskType = Integer.parseInt(type);
			request.setAttribute("taskType", taskType);
		}
		if (price != null && !price.equals("")) {
			taskPrice = Integer.parseInt(price);
			request.setAttribute("taskPrice", taskPrice);
		}
		 //分页
	      Pager pagelist = userTaskService.queryMyTaskZt(10, page, user.getId(), taskStatus, taskType, taskPrice);
	      List pagetask = pagelist.getList();
	      int Total = pagelist.getTotalPage();
//	    List<UserTask> list = userTaskService.shaixuan(user1.getId(), taskStatus1, taskType1,taskPrice1);
//	    	request.setAttribute("list", list);
	    	request.setAttribute("openId", openId);
	    	request.setAttribute("Total", Total);
	    	request.setAttribute("page", page);
	    	request.setAttribute("pagetask", pagetask);
		return "index";
	}

	/**
	 * 分页查询app任务
	 * 
	 * @return
	 */
	public String queryAuditTask() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		pageBean = userTaskService.queryAppTaskPage(10, page, search);
		usertaskList = pageBean.getList();
		request.setAttribute("usertaskList", usertaskList);
		request.setAttribute("pageBean", pageBean);
		return "queryAuditTask";

	}

	/**
	 * 审核页面
	 * 
	 * @return
	 */
	public String queryAuditPage() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		usertask = userTaskService.queryUserTaskInfo(usertask.getUserTaskId());
		shotList = userTaskService.queryShotList(usertask);
		user = userService.queryuserById(user.getId());
		request.setAttribute("usertask", usertask);
		request.setAttribute("shotList", shotList);

		return "queryAuditPage";
	}

	/**
	 * 审核通过
	 * 
	 * @return
	 */
	public String queryAudit() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		//通过我任务的id查询  我所接任务的信息 
		UserTask usertask1 = userTaskService.queryUserTaskInfo(usertask
				.getUserTaskId());
		if(usertask1.getTaskStatus()==2){
			msg="该任务已完成";
			return "queryAuditPage";
			
		}
		//修改任务状态
		usertask1.setTaskStatus(2);
		//设置任务审核结果
			usertask1.setTaskReson(usertask.getTaskReson());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sd = sdf.format(date);
		usertask1.setTaskCompletionTime(sd);
		//查询出任务
	         Long taskId = usertask.getTaskId();
	         Task task=taskService.queryTaskById(taskId);
			//RecomCode图鉴人推荐码
		User user1 = userService.queryuserById(user.getId());
		//通过图鉴人推荐码查询出推荐用户的信息
		User user2 = userService.queryUserSadff(user1.getRecomCode());
		if (user2 != null) {
			//user1.getUserLevel()当前角色的等级
			double yonjing = (usertask.getTaskBonus() / 0.3) * 0.1;
			if (user1.getUserLevel() == 1) {
//				double x1 = (usertask.getTaskBonus() * 0.3) * 0.1;
				//团队佣金
				
				if (user2.getPromotionCommission() == null
						|| user2.getPromotionCommission() == 0) {
					user2.setPromotionCommission(yonjing);
				} else {
					//添加扩佣金
					user2.setPromotionCommission(user2.getPromotionCommission()
							+ yonjing);
				}
				if (user2.getTotalMoney() != null && !"".equals(user2.getTotalMoney())) {
					user2.setTotalMoney(user2.getTotalMoney()
							+ yonjing);
				} else {
					user2.setTotalMoney(yonjing);
				}
				Commissionrecord commissionrecord1 = new Commissionrecord();
				commissionrecord1.setRecordTime(sd);
				commissionrecord1.setTaskTitle(usertask1.getTaskTitle());
				commissionrecord1.setTaskType(usertask1.getTaskType());
				commissionrecord1.setTaskMoney(yonjing);
				commissionrecord1.setRecordType(2);
				commissionrecord1.setUser(user2);
				commissionrecordService.addCommissionrecord(commissionrecord1);
			}
			//判断等级来算出团队y
//				double x2 = (usertask.getTaskBonus() * 0.3) * 0.05;
			double yongjin2;
			if(user1.getUserLevel() == 1){
				yongjin2  = (usertask.getTaskBonus() / 0.3) * 0.05;
			}else {
				yongjin2  = (usertask.getTaskBonus() / 0.4) * 0.05;
			}
				if (user2.getTeamCommissions() == null
						|| user2.getTeamCommissions() == 0) {
					user2.setTeamCommissions(yongjin2);
					
				} else {
					user2.setTeamCommissions(user2.getTeamCommissions() + yongjin2);
				}
				if(user1.getUserLevel() == 1){	
					if(user2.getBalance()==null||user2.getBalance()==0){						
						user2.setBalance(yongjin2+yonjing);
					}else {
						user2.setBalance(user2.getBalance() + yongjin2+yonjing);
					}
//					user2.setFreezingAmount(user2.getFreezingAmount() + yongjin2+yonjing);
//					System.out.println("user2.getFreezingAmount():-------"+user2.getFreezingAmount());
				}else {
					if(user2.getBalance()==null||user2.getBalance()==0){	
//						user2.setFreezingAmount(yongjin2);
						user2.setBalance(yongjin2);
					}else {
//						user2.setFreezingAmount(user2.getFreezingAmount()+yongjin2);
						user2.setBalance(user2.getBalance()+yongjin2);
					}
				}
				Commissionrecord commissionrecord2 = new Commissionrecord();
				commissionrecord2.setRecordTime(sd);
				commissionrecord2.setTaskTitle(usertask1.getTaskTitle());
				commissionrecord2.setTaskType(usertask1.getTaskType());
				commissionrecord2.setTaskMoney(yongjin2);
				commissionrecord2.setRecordType(2);
				commissionrecord2.setUser(user2);
				commissionrecordService.addCommissionrecord(commissionrecord2);
		}
		if (user1.getTaskNum() != null && !"".equals(user1.getTaskNum())) {
			user1.setTaskNum(user1.getTaskNum() + 1);
		} else {
			user1.setTaskNum(1);
		}
		if (user1.getTotalMoney() != null && !"".equals(user1.getTotalMoney())) {
			user1.setTotalMoney(user1.getTotalMoney()
					+ usertask.getTaskBonus());
		} else {
			user1.setTotalMoney(usertask.getTaskBonus());
		}
		/*
		 * if(user1.getTaskCommission()!=null&&!"".equals(user1.getTaskCommission
		 * ())){
		 * 
		 * user1.setTaskCommission(user1.getTaskCommission()+usertask1.getTaskBonus
		 * ()); }else{ user1.setTaskCommission(usertask1.getTaskBonus()); }
		 */
		//冻结金额
//		if (user1.getFreezingAmount() != null
//				&& !"".equals(user1.getFreezingAmount())) {
//			user1.setFreezingAmount(user1.getFreezingAmount()
//					+ usertask.getTaskBonus());
//		} else {
//			user1.setFreezingAmount(usertask.getTaskBonus());
//		}
		if (user1.getBalance() != null
				&& !"".equals(user1.getFreezingAmount())) {
			user1.setBalance(user1.getBalance()
					+ usertask.getTaskBonus());
		} else {
			user1.setBalance(usertask.getTaskBonus());
		}

		if (user1.getTotalMoney() >= 3000) {
			user1.setUserLevel(2);
		}
		int a = userService.updateUser(user1);
		task = taskService.queryTaskById(usertask1.getTaskId());
		// task.setTaskSurplus(task.getTaskSurplus()-1);
//		task.setTaskRemainderNumber(task.getTaskRemainderNumber() - 1);
		task.setTaskSBonus(task.getTaskSBonus() - usertask1.getTaskBonus());
		int b = taskService.updateTask(task);
		// 佣金记录 收入记录
		commissionrecord = new Commissionrecord();
		commissionrecord.setRecordTime(sd);
		commissionrecord.setTaskTitle(usertask1.getTaskTitle());
		commissionrecord.setTaskType(usertask1.getTaskType());
		commissionrecord.setTaskMoney(usertask1.getTaskBonus());
		commissionrecord.setRecordType(1);
		commissionrecord.setUser(user1);
		int c = commissionrecordService.addCommissionrecord(commissionrecord);
		/*incomeRecode = new IncomeRecode();
		incomeRecode.setIncomeMoney(usertask1.getTaskBonus());
		incomeRecode.setIncomeStatus(1);
		incomeRecode.setIncomeTime(sd);
		incomeRecode.setUser(user1);
		int d = incomeRecodeService.addIncomeRecode(incomeRecode);*/
		freeAmount = new FreeAmount();
		freeAmount.setFreeStatus(1);
		freeAmount.setTaskMoney(usertask1.getTaskBonus());
		freeAmount.setTaskTitle(usertask1.getTaskTitle());
		freeAmount.setRecordTime(sd);
		Calendar cld = Calendar.getInstance();
		cld.set(Calendar.YEAR, date.getYear());
		cld.set(Calendar.MONDAY, date.getMonth());
		cld.set(Calendar.DATE, date.getDay());
		cld.set(Calendar.HOUR, date.getHours());
		cld.set(Calendar.MINUTE, date.getMinutes());
		cld.set(Calendar.SECOND, date.getSeconds());
		// 调用Calendar类中的add()，增加时间量
		cld.add(Calendar.DATE, 7);
		Date dt = cld.getTime();
		String sdt = sdf.format(dt);
		freeAmount.setThawTime(sdt);
		freeAmount.setTaskType(usertask1.getTaskType());
		freeAmountService.addFreeAmount(freeAmount);

		int i = userTaskService.updateUserTask(usertask1);
		return queryAuditTask();
	}

	/**
	 * 审核不通过
	 * 
	 * @return
	 */
	public String queryAuditNo() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		UserTask usertask1 = userTaskService.queryUserTaskInfo(usertask
				.getUserTaskId());
		usertask1.setTaskStatus(3);
		usertask1.setTaskReson(usertask.getTaskReson());
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String sd = sdf.format(date);
		usertask1.setTaskCompletionTime(sd);
		//获取任务的id
		        Task task2 = new Task();
		    Long taskid = usertask1.getTaskId();
		        Task task1 = taskService.queryTaskById(taskid);
		        task1.setTaskId(taskid);
		if(task1.getTaskRemainderNumber()!=null&&task1.getTaskRemainderNumber()!=0){
			task1.setTaskRemainderNumber(task1.getTaskRemainderNumber()+1);
		}else {
			task1.setTaskRemainderNumber(1);
		}
		int i1 = taskService.updateTask(task1);
		int i = userTaskService.updateUserTask(usertask1);
		return queryAuditTask();
	}

	/**
	 * 分页查询已审核的任务
	 * 
	 * @return
	 */
	public String queryAuditUserTask() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		pageBean = userTaskService.queryAllTaskPage(3, page, search);
		usertaskList = pageBean.getList();
		request.setAttribute("usertaskList", usertaskList);
		request.setAttribute("pageBean", pageBean);
		return "queryAuditUserTask";

	}

	/**
	 * 批量删除
	 * 
	 * @return
	 */
	public String deleteAllTask() {

		int i = userTaskService.deleteUserTask(number);
		return queryAuditUserTask();

	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String deleteUserTask() {

		int i = userTaskService.deleteTask(usertask.getUserTaskId());
		return queryAuditUserTask();

	}

	public String uploadTime() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap = new HashMap<String, Object>();
		String userTaskId = request.getParameter("taskId");
		String openId = request.getParameter("openId");
		UserTask userTask = userTaskService.queryUserTaskById(Long
				.parseLong(userTaskId));
		userTaskService.updateUserTask(userTask);
		dataMap.put("msg", 1);
		return "dataMap";
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public UserTaskService getUserTaskService() {
		return userTaskService;
	}

	public void setUserTaskService(UserTaskService userTaskService) {
		this.userTaskService = userTaskService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public List<UserTask> getUsertaskList() {
		return usertaskList;
	}

	public void setUsertaskList(List<UserTask> usertaskList) {
		this.usertaskList = usertaskList;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public List<TaskScreenshot> getShotList() {
		return shotList;
	}

	public void setShotList(List<TaskScreenshot> shotList) {
		this.shotList = shotList;
	}

	public Pager getPageBean() {
		return pageBean;
	}

	public void setPageBean(Pager pageBean) {
		this.pageBean = pageBean;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public UserTask getUsertask() {
		return usertask;
	}

	public void setUsertask(UserTask usertask) {
		this.usertask = usertask;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	public Commissionrecord getCommissionrecord() {
		return commissionrecord;
	}

	public void setCommissionrecord(Commissionrecord commissionrecord) {
		this.commissionrecord = commissionrecord;
	}

	public IncomeRecode getIncomeRecode() {
		return incomeRecode;
	}

	public void setIncomeRecode(IncomeRecode incomeRecode) {
		this.incomeRecode = incomeRecode;
	}

	public File getFileTest() {
		return fileTest;
	}

	public void setFileTest(File fileTest) {
		this.fileTest = fileTest;
	}

	public String getFileTestFileName() {
		return fileTestFileName;
	}

	public void setFileTestFileName(String fileTestFileName) {
		this.fileTestFileName = fileTestFileName;
	}

	public File getFileTest1() {
		return fileTest1;
	}

	public void setFileTest1(File fileTest1) {
		this.fileTest1 = fileTest1;
	}

	public String getFileTest1FileName() {
		return fileTest1FileName;
	}

	public void setFileTest1FileName(String fileTest1FileName) {
		this.fileTest1FileName = fileTest1FileName;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public CommissionrecordService getCommissionrecordService() {
		return commissionrecordService;
	}

	public void setCommissionrecordService(
			CommissionrecordService commissionrecordService) {
		this.commissionrecordService = commissionrecordService;
	}

	public IncomeRecodeService getIncomeRecodeService() {
		return incomeRecodeService;
	}

	public void setIncomeRecodeService(IncomeRecodeService incomeRecodeService) {
		this.incomeRecodeService = incomeRecodeService;
	}

	public FreeAmountService getFreeAmountService() {
		return freeAmountService;
	}

	public void setFreeAmountService(FreeAmountService freeAmountService) {
		this.freeAmountService = freeAmountService;
	}

	public FreeAmount getFreeAmount() {
		return freeAmount;
	}

	public void setFreeAmount(FreeAmount freeAmount) {
		this.freeAmount = freeAmount;
	}

}
